package com.cooldatasoft.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.cooldatasoft.base.RootServiceImpl;
import com.cooldatasoft.data.ComboValue;
import com.cooldatasoft.data.Node;
import com.cooldatasoft.data.PersonNodeMapping;
import com.cooldatasoft.data.User;
import com.cooldatasoft.service.NodeService;

public class NodeServiceImpl extends RootServiceImpl implements NodeService {

	public List<Node> getNodeList() {
		return getNodeDAO().find("from Node where deleted=false");
	}

	public Node get(Integer entityId) {
		return getNodeDAO().get(entityId);
	}

	public void deleteNodeById(Integer entityId, User currentUser) {
		Node nodeToBeDeleted = getNodeDAO().get(entityId);
		
		nodeToBeDeleted.setUpdateDate(new Date());
		nodeToBeDeleted.setUpdateUserId(currentUser.getId());
		nodeToBeDeleted.setDeleted(true);
		
		getNodeDAO().saveOrUpdate(nodeToBeDeleted);
	}

	public List<ComboValue> getNodeSelectOptions() {
		List<Node> nodeList = getNodeList();
		List<ComboValue> optionList = new ArrayList<ComboValue>();				
		for(Node node:nodeList){			
			optionList.add(new ComboValue(node.getId(),node.getLabel()));
		}		
		return optionList;
	}

	public List<Node> getChildrenNodeList(Integer rootNodeId) {
		return getNodeDAO().find("from Node where deleted=false AND parentId = "+rootNodeId+" AND id != 1");
	}

	public void saveOrUpdate(Node node) {
		getNodeDAO().saveOrUpdate(node);
	}

	public List<Node> getNodeListRemoveRootAndCEO() {
		return getNodeDAO().find("from Node where deleted=false and id>2");
	}

	public PersonNodeMapping getPersonNodeMappingByPersonId(Integer personId) {
		// TODO Auto-generated method stub
		List<PersonNodeMapping> personNodeMappingList = getPersonNodeMappingDAO().find("from PersonNodeMapping where deleted=false AND personId = "+personId);
		if(personNodeMappingList.size() == 1){
			return personNodeMappingList.get(0);
		}else{
			return null;
		}
	}

	public void saveOrUpdate(PersonNodeMapping entity) {
		getPersonNodeMappingDAO().saveOrUpdate(entity);
	}

	
}
